package nats_controller

import (
	"gluenet/modules/manager/server/domain"
	"gluenet/modules/manager/server/domain/vo"
	"gluenet/modules/manager/server/infra"
	"gluenet/modules/manager/server/infra/prepare"
)

func init() {
	prepare.RegisterNatsController(func() {
		controller := NewInstance()
		prepare.InjectNatsController(func() *Instance {
			return controller
		})
	})
}

type Instance struct {
	Instance *domain.Instance
}

func NewInstance() *Instance {
	r := &Instance{}
	prepare.FetchDependency(&r.Instance)
	return r
}

// Nats serves
// Topic: v2.rpc.apis.instance.report
func (r *Instance) Report(req vo.InstanceReport) *infra.Response {
	err := r.Instance.SaveReport(&req)
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(nil)
}

// Nats serves
// Topic: v2.rpc.apis.instance.import
func (r *Instance) Import(req vo.ImportInstanceReq) *infra.Response {
	//log.Printf("import")
	obj, err := r.Instance.Import(&req)
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(obj)
}

//// Nats serves
//// Topic: v2.rpc.apis.instance.importbacth
//func (r *Instance) ImportBacth(reqs []vo.ImportInstanceReq) *infra.Response {
//	var objs []interface{}
//	var errs []error
//	for _, v := range reqs {
//		obj, err := r.Instance.Import(&v)
//		if err != nil {
//			errs = append(errs, err)
//		} else {
//			objs = append(objs, obj)
//		}
//	}
//	if len(errs) == 0 {
//		return infra.ResponseReqErr(fmt.Errorf("errs : %v", errs), nil)
//	}
//	return infra.ResponseOK(objs)
//}

// Nats serves
// Topic: v2.rpc.apis.instance.delimport
func (r *Instance) DelImport(req vo.ImportInstanceReq) *infra.Response {
	obj, err := r.Instance.DelImport(req.Guid, req.UserID)
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(obj)
}

// Nats serves
// Topic: v2.rpc.apis.instance.getagent
func (r *Instance) GetAgent(req vo.InstanceContinaerAgentReq) *infra.Response {
	obj, err := r.Instance.GetInstanceContainerAgent(req.Guid, req.Container)
	if err != nil {
		return infra.ResponseReqErr(err, nil)
	}
	return infra.ResponseOK(obj)
}
